package com.gitee.wsl.struct.page


class Page<T>(var datas: List<T> = arrayListOf()) {

    val dataSize:Int
        get() = datas.size

    var countSize: Int = 0

    var pageSize: Int = 0

    var pageIndex: Int = 0

    val realDataIndex:Int
        get() = pageIndex * pageSize

    val hasNext:Boolean
        get() = dataSize > 0 && realDataIndex+dataSize < countSize

    companion object{
        fun <T> emptyPage()=Page<T>()

        /**
         * 分页彩虹算法<br></br>
         * 来自：[ https://github.com/iceroot/iceroot/blob/master/src/main/java/com/icexxx/util/IceUtil.java](https://github.com/iceroot/iceroot/blob/master/src/main/java/com/icexxx/util/IceUtil.java)<br></br>
         * 通过传入的信息，生成一个分页列表显示
         *
         * @param pageNo       当前页
         * @param totalPage    总页数
         * @param displayCount 每屏展示的页数
         * @return 分页条
         */
        fun rainbow(pageNo: Int, totalPage: Int, displayCount: Int=10): IntArray {
            // displayCount % 2
            val isEven = displayCount and 1 == 0
            val left = displayCount shr 1
            var right = displayCount shr 1
            var length = displayCount
            if (isEven) {
                right++
            }
            if (totalPage < displayCount) {
                length = totalPage
            }
            val result = IntArray(length)
            if (totalPage >= displayCount) {
                if (pageNo <= left) {
                    for (i in result.indices) {
                        result[i] = i + 1
                    }
                } else if (pageNo > totalPage - right) {
                    for (i in result.indices) {
                        result[i] = i + totalPage - displayCount + 1
                    }
                } else {
                    for (i in result.indices) {
                        result[i] = i + pageNo - left + if (isEven) 1 else 0
                    }
                }
            } else {
                for (i in result.indices) {
                    result[i] = i + 1
                }
            }
            return result
        }
    }
}

fun <T> List<T>.toPage(size: Int = 50, page: Int = 1): Page<T> {
    val preIndex = (size * (page - 1))
    val dataSize = this.size
    val fromIndex = if (preIndex < 0) 0 else preIndex
    if (fromIndex > this.size) return Page.emptyPage()
    val toIndex = if (fromIndex + size > this.size) fromIndex + (this.size - fromIndex) else fromIndex + size
    val datas = this.subList(fromIndex, toIndex)
    return Page(datas).apply {
        this.countSize = dataSize
        this.pageSize=size
        this.pageIndex=page
    }
}